<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CTO.new 管理后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
        }

        .header {
            background: white;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 28px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #333;
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            background: #4ade80;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .test-button {
            background: #333;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .test-button:hover {
            background: #555;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 24px;
            border: 1px solid #e0e0e0;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: #333;
        }

        .stat-label {
            font-size: 14px;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .stat-value {
            font-size: 36px;
            font-weight: bold;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .stat-icon {
            font-size: 48px;
            opacity: 0.2;
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
        }

        .tabs {
            background: white;
            border-radius: 8px;
            padding: 0;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
            overflow: hidden;
        }

        .tab-buttons {
            display: flex;
            border-bottom: 2px solid #f3f4f6;
        }

        .tab-button {
            flex: 1;
            padding: 16px;
            background: none;
            border: none;
            font-size: 15px;
            cursor: pointer;
            color: #666;
            transition: all 0.2s;
            position: relative;
        }

        .tab-button.active {
            color: #333;
            font-weight: 600;
        }

        .tab-button.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            right: 0;
            height: 2px;
            background: #333;
        }

        .tab-content {
            padding: 24px;
        }

        .tab-pane {
            display: none;
        }

        .tab-pane.active {
            display: block;
        }

        .add-cookie-form {
            background: #fafafa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #666;
        }

        .form-group textarea {
            min-height: 100px;
            resize: vertical;
            font-family: monospace;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
        }

        .btn-primary {
            background: #333;
            color: white;
        }

        .btn-primary:hover {
            background: #555;
        }

        .btn-test {
            background: #555;
            color: white;
        }

        .btn-test:hover {
            background: #666;
        }

        .btn-edit {
            background: #777;
            color: white;
        }

        .btn-edit:hover {
            background: #888;
        }

        .btn-disable {
            background: #999;
            color: white;
        }

        .btn-disable:hover {
            background: #aaa;
        }

        .btn-delete {
            background: #333;
            color: white;
            border: 1px solid #333;
        }

        .btn-delete:hover {
            background: white;
            color: #333;
        }

        .cookie-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .cookie-item {
            background: #fafafa;
            border: 1px solid #d0d0d0;
            border-radius: 8px;
            padding: 20px;
            transition: all 0.2s;
        }

        .cookie-item:hover {
            border-color: #999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .cookie-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .cookie-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .cookie-status {
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .cookie-status.active {
            background: #333;
            color: white;
        }

        .cookie-status.inactive {
            background: #e0e0e0;
            color: #666;
        }

        .cookie-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 12px;
            margin-bottom: 12px;
            font-size: 14px;
            color: #6b7280;
        }

        .cookie-value {
            background: white;
            padding: 12px;
            border-radius: 8px;
            font-family: monospace;
            font-size: 12px;
            color: #374151;
            word-break: break-all;
            max-height: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .cookie-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6b7280;
        }

        .empty-state-icon {
            font-size: 64px;
            margin-bottom: 16px;
            opacity: 0.3;
        }

        .config-section {
            background: #fafafa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }

        .config-section h3 {
            margin-bottom: 16px;
            color: #333;
            font-weight: 600;
        }

        .config-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .config-item:last-child {
            border-bottom: none;
        }

        .config-label {
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .config-value {
            color: #666;
            font-family: monospace;
            font-size: 13px;
        }

        .monitor-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .monitor-card {
            background: #fafafa;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        .monitor-card h3 {
            margin-bottom: 16px;
            color: #333;
            font-weight: 600;
        }

        .monitor-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            font-size: 14px;
        }

        .monitor-label {
            color: #666;
        }

        .monitor-value {
            color: #333;
            font-weight: 600;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal.show {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            margin-bottom: 20px;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
            font-size: 20px;
            font-weight: 600;
        }

        .modal-body .form-group {
            margin-bottom: 20px;
        }

        .modal-body label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
            font-size: 14px;
        }

        .modal-body input,
        .modal-body textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #d0d0d0;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        .modal-body textarea {
            min-height: 100px;
            font-family: monospace;
            resize: vertical;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .modal-footer .btn {
            padding: 10px 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>
            ⚙️ CTO.new 管理后台
        </h1>
        <div style="display: flex; align-items: center; gap: 16px;">
            <div class="status-badge">
                <div class="status-dot"></div>
                服务运行中
            </div>
            <button class="test-button" onclick="testChatAPI()">💬 聊天测试</button>
            <button class="test-button" onclick="logout()" style="background: #999;">🚪 退出</button>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label">总请求数</div>
            <div class="stat-value" id="totalRequests">0</div>
            <div class="stat-icon">📊</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">成功请求</div>
            <div class="stat-value" id="successRequests">0</div>
            <div class="stat-icon">✅</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">总会话数</div>
            <div class="stat-value" id="totalConversations">0</div>
            <div class="stat-icon">💬</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">活跃会话</div>
            <div class="stat-value" id="activeConversations">0</div>
            <div class="stat-icon">🗨️</div>
        </div>
    </div>

    <div class="tabs">
        <div class="tab-buttons">
            <button class="tab-button active" onclick="switchTab('cookies')">🍪 Cookie管理</button>
            <button class="tab-button" onclick="switchTab('conversations')">💬 会话管理</button>
            <button class="tab-button" onclick="switchTab('schedule')">📅 实时日志</button>
            <button class="tab-button" onclick="switchTab('config')">⚙️ 系统配置</button>
            <button class="tab-button" onclick="switchTab('monitor')">📈 系统监控</button>
        </div>

        <div class="tab-content">
            <!-- Cookie 管理 -->
            <div id="tab-cookies" class="tab-pane active">
                <div class="add-cookie-form">
                    <h3 style="margin-bottom: 16px; color: #1f2937;">➕ 添加Cookie</h3>
                    <form onsubmit="addCookie(event)">
                        <div class="form-group">
                            <label>主账号</label>
                            <input type="text" id="cookieName" placeholder="例如: 主账号" required>
                        </div>
                        <div class="form-group">
                            <label>Cookie 值</label>
                            <textarea id="cookieValue" placeholder="粘贴完整的 Cookie 字符串..." required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">添加Cookie</button>
                    </form>
                </div>

                <div id="cookieList" class="cookie-list">
                    <!-- Cookie 列表将动态加载 -->
                </div>
            </div>

            <!-- 会话管理 -->
            <div id="tab-conversations" class="tab-pane">
                <div class="config-section">
                    <h3>💬 会话管理</h3>
                    <button class="btn btn-primary" onclick="loadConversations()" style="margin-bottom: 20px;">🔄 刷新</button>
                    <div id="conversationsList"></div>
                </div>
            </div>

            <!-- 实时日志 -->
            <div id="tab-schedule" class="tab-pane">
                <div class="config-section">
                    <h3>📋 实时日志</h3>
                    <div style="background: #1f2937; color: #e5e7eb; padding: 20px; border-radius: 8px; font-family: 'Consolas', 'Courier New', monospace; font-size: 13px; max-height: 500px; overflow-y: auto; line-height: 1.6;" id="logContainer">
                        <div style="color: #9ca3af;">等待日志加载...</div>
                    </div>
                </div>
            </div>

            <!-- 系统配置 -->
            <div id="tab-config" class="tab-pane">
                <div class="config-section">
                    <h3>🔧 API 配置</h3>
                    <div class="config-item">
                        <div class="config-label">API 基础地址</div>
                        <div class="config-value">https://api.enginelabs.ai</div>
                    </div>
                    <div class="config-item">
                        <div class="config-label">Clerk 基础地址</div>
                        <div class="config-value">https://clerk.cto.new</div>
                    </div>
                    <div class="config-item">
                        <div class="config-label">源站地址</div>
                        <div class="config-value">https://cto.new</div>
                    </div>
                    <div class="config-item">
                        <div class="config-label">服务端口</div>
                        <div class="config-value">8000</div>
                    </div>
                </div>

                <div class="config-section">
                    <h3>🤖 可用模型</h3>
                    <div class="config-item">
                        <div class="config-label">Claude Sonnet 4.5</div>
                        <div class="config-value">ClaudeSonnet4_5</div>
                    </div>
                    <div class="config-item">
                        <div class="config-label">GPT-5</div>
                        <div class="config-value">GPT5</div>
                    </div>
                </div>
            </div>

            <!-- 系统监控 -->
            <div id="tab-monitor" class="tab-pane">
                <div class="monitor-grid">
                    <div class="monitor-card">
                        <h3>📊 请求统计</h3>
                        <div class="monitor-item">
                            <span class="monitor-label">总请求数</span>
                            <span class="monitor-value" id="monitorTotalRequests">0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">成功请求</span>
                            <span class="monitor-value" id="monitorSuccessRequests">0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">成功率</span>
                            <span class="monitor-value" id="monitorSuccessRate">0%</span>
                        </div>
                    </div>

                    <div class="monitor-card">
                        <h3>🍪 Cookie 状态</h3>
                        <div class="monitor-item">
                            <span class="monitor-label">活跃 Cookie</span>
                            <span class="monitor-value" id="monitorActiveCookies">0</span>
                        </div>
                        <div class="monitor-item">
                            <span class="monitor-label">总 Cookie 数</span>
                            <span class="monitor-value" id="monitorTotalCookies">0</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑 Cookie 模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>✏️ 编辑 Cookie</h2>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="editCookieName">Cookie 名称</label>
                    <input type="text" id="editCookieName" placeholder="例如: 主账号">
                </div>
                <div class="form-group">
                    <label for="editCookieValue">Cookie 值</label>
                    <textarea id="editCookieValue" placeholder="粘贴完整的 Cookie 字符串..."></textarea>
                    <small style="color: #999; font-size: 12px;">💡 留空表示不修改 Cookie 值</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: #999;" onclick="closeEditModal()">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveEditCookie()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 检查登录状态
        const adminKey = localStorage.getItem('adminKey');
        if (!adminKey) {
            window.location.href = '/admin/login';
        }

        // 全局请求配置
        const fetchWithAuth = (url, options = {}) => {
            return fetch(url, {
                ...options,
                headers: {
                    ...options.headers,
                    'Authorization': `Bearer ${adminKey}`
                }
            }).then(async response => {
                if (response.status === 401) {
                    // 认证失败，清除密钥并跳转到登录页
                    localStorage.removeItem('adminKey');
                    alert('认证失败，请重新登录');
                    window.location.href = '/admin/login';
                    throw new Error('Unauthorized');
                }
                return response;
            });
        };

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('adminKey');
                window.location.href = '/admin/login';
            }
        }

        // 切换标签页
        function switchTab(tabName) {
            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));
            
            event.target.classList.add('active');
            document.getElementById(`tab-${tabName}`).classList.add('active');
        }

        // 加载统计数据
        async function loadStats() {
            try {
                const response = await fetchWithAuth('/admin/api/stats');
                const stats = await response.json();
                
                document.getElementById('totalRequests').textContent = stats.totalRequests;
                document.getElementById('successRequests').textContent = stats.successRequests;
                document.getElementById('totalConversations').textContent = stats.totalConversations || 0;
                document.getElementById('activeConversations').textContent = stats.activeConversations || 0;
                
                document.getElementById('monitorTotalRequests').textContent = stats.totalRequests;
                document.getElementById('monitorSuccessRequests').textContent = stats.successRequests;
                document.getElementById('monitorActiveCookies').textContent = stats.activeCookies;
                
                const successRate = stats.totalRequests > 0 
                    ? ((stats.successRequests / stats.totalRequests) * 100).toFixed(1)
                    : 0;
                document.getElementById('monitorSuccessRate').textContent = successRate + '%';
            } catch (error) {
                console.error('加载统计数据失败:', error);
            }
        }

        // 加载 Cookie 列表
        async function loadCookies() {
            try {
                const response = await fetchWithAuth('/admin/api/cookies');
                const cookies = await response.json();
                
                const container = document.getElementById('cookieList');
                document.getElementById('monitorTotalCookies').textContent = cookies.length;
                
                if (cookies.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <div class="empty-state-icon">🍪</div>
                            <h3>暂无 Cookie</h3>
                            <p>请添加第一个 Cookie 开始使用</p>
                        </div>
                    `;
                    return;
                }
                
                container.innerHTML = cookies.map(cookie => `
                    <div class="cookie-item">
                        <div class="cookie-header">
                            <div class="cookie-name">
                                🏷️ ${cookie.name}
                                <span class="cookie-status ${cookie.status}">${cookie.status === 'active' ? '启用中' : '已禁用'}</span>
                            </div>
                        </div>
                        <div class="cookie-info">
                            <div>📅 创建时间: ${new Date(cookie.createdAt).toLocaleString('zh-CN')}</div>
                            <div>🔢 使用次数: ${cookie.requestCount}</div>
                            <div>⏰ 最后使用: ${cookie.lastUsed ? new Date(cookie.lastUsed).toLocaleString('zh-CN') : '未使用'}</div>
                        </div>
                        <div class="cookie-value">${cookie.cookie.substring(0, 100)}...</div>
                        <div class="cookie-actions">
                            <button class="btn btn-test" onclick="testCookie('${cookie.id}')">测试</button>
                            <button class="btn btn-edit" onclick="editCookie('${cookie.id}')">编辑</button>
                            <button class="btn btn-disable" onclick="toggleCookie('${cookie.id}', '${cookie.status}')">
                                ${cookie.status === 'active' ? '禁用' : '启用'}
                            </button>
                            <button class="btn btn-delete" onclick="deleteCookie('${cookie.id}')">删除</button>
                        </div>
                    </div>
                `).join('');
            } catch (error) {
                console.error('加载 Cookie 列表失败:', error);
            }
        }

        // 添加 Cookie
        async function addCookie(event) {
            event.preventDefault();
            
            const name = document.getElementById('cookieName').value;
            const cookie = document.getElementById('cookieValue').value;
            
            try {
                const response = await fetchWithAuth('/admin/api/cookies', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name, cookie })
                });
                
                if (response.ok) {
                    alert('✅ Cookie 添加成功！');
                    document.getElementById('cookieName').value = '';
                    document.getElementById('cookieValue').value = '';
                    loadCookies();
                    loadStats();
                } else {
                    alert('❌ 添加失败，请检查 Cookie 格式');
                }
            } catch (error) {
                alert('❌ 添加失败: ' + error.message);
            }
        }

        // 测试 Cookie
        async function testCookie(id) {
            try {
                const response = await fetchWithAuth(`/admin/api/cookies/${id}/test`, {
                    method: 'POST'
                });
                const result = await response.json();
                
                if (result.valid) {
                    alert(`✅ Cookie 有效！\n\nSession ID: ${result.sessionId || 'N/A'}`);
                } else {
                    alert(`❌ Cookie 已失效\n\n错误信息：${result.error || '未知错误'}\n\n请到 cto.new 重新登录并获取新的 Cookie`);
                }
            } catch (error) {
                alert('❌ 测试失败: ' + error.message);
            }
        }

        // 切换 Cookie 状态
        async function toggleCookie(id, currentStatus) {
            const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
            
            try {
                const response = await fetchWithAuth(`/admin/api/cookies/${id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: newStatus })
                });
                
                if (response.ok) {
                    loadCookies();
                    loadStats();
                }
            } catch (error) {
                alert('❌ 操作失败: ' + error.message);
            }
        }

        // 删除 Cookie
        async function deleteCookie(id) {
            if (!confirm('确定要删除这个 Cookie 吗？')) return;
            
            try {
                const response = await fetchWithAuth(`/admin/api/cookies/${id}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    alert('✅ 删除成功！');
                    loadCookies();
                    loadStats();
                }
            } catch (error) {
                alert('❌ 删除失败: ' + error.message);
            }
        }

        // 当前编辑的 Cookie ID
        let currentEditCookieId = null;

        // 编辑 Cookie
        async function editCookie(id) {
            try {
                // 获取现有 Cookie 数据
                const response = await fetchWithAuth(`/admin/api/cookies/${id}`);
                const cookie = await response.json();
                
                // 填充表单
                document.getElementById('editCookieName').value = cookie.name;
                document.getElementById('editCookieValue').value = '';
                currentEditCookieId = id;
                
                // 显示模态框
                document.getElementById('editModal').classList.add('show');
            } catch (error) {
                alert('❌ 获取 Cookie 信息失败: ' + error.message);
            }
        }

        // 关闭编辑模态框
        function closeEditModal() {
            document.getElementById('editModal').classList.remove('show');
            currentEditCookieId = null;
        }

        // 保存编辑
        async function saveEditCookie() {
            if (!currentEditCookieId) return;
            
            const newName = document.getElementById('editCookieName').value.trim();
            const newCookieValue = document.getElementById('editCookieValue').value.trim();
            
            if (!newName) {
                alert('❌ Cookie 名称不能为空');
                return;
            }
            
            try {
                // 构建更新数据
                const updateData = { name: newName };
                if (newCookieValue) {
                    updateData.cookie = newCookieValue;
                }
                
                // 发送更新请求
                const response = await fetchWithAuth(`/admin/api/cookies/${currentEditCookieId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(updateData)
                });
                
                if (response.ok) {
                    alert('✅ 更新成功！');
                    closeEditModal();
                    loadCookies();
                } else {
                    const error = await response.json();
                    alert(`❌ 更新失败: ${error.error || '未知错误'}`);
                }
            } catch (error) {
                alert('❌ 保存失败: ' + error.message);
            }
        }

        // 点击模态框背景关闭
        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });

        // 测试聊天 API
        function testChatAPI() {
            alert('请使用 API 客户端测试聊天接口\n\nPOST /v1/chat/completions\nAuthorization: Bearer YOUR_COOKIE');
        }

        // 初始化
        loadStats();
        loadCookies();
        
        // 定时刷新
        setInterval(() => {
            loadStats();
            loadCookies();
        }, 5000);

        // 连接实时日志 SSE
        let eventSourceInstance = null;
        function connectLogs() {
            const logContainer = document.getElementById('logContainer');
            
            // 显示连接状态
            logContainer.innerHTML = '<div style="color: #f59e0b;">正在连接日志服务器...</div>';
            
            // EventSource 不支持自定义 header，通过 URL 参数传递密钥
            const url = `/admin/api/logs/stream?token=${encodeURIComponent(adminKey)}`;
            console.log('连接日志 SSE:', url);
            
            try {
                eventSourceInstance = new EventSource(url);

                eventSourceInstance.onopen = () => {
                    console.log('✅ 日志连接已建立');
                    logContainer.innerHTML = '<div style="color: #10b981;">✅ 日志连接成功，等待日志...</div>';
                };

                eventSourceInstance.onmessage = (event) => {
                    try {
                        // 清除初始提示
                        if (logContainer.children.length === 1 && logContainer.firstChild.textContent.includes('等待日志')) {
                            logContainer.innerHTML = '';
                        }
                        
                        const log = JSON.parse(event.data);
                        const logLine = document.createElement('div');
                        logLine.style.marginBottom = '4px';
                        
                        // 根据日志级别设置颜色
                        let color = '#e5e7eb'; // 默认灰白色
                        if (log.level === 'ERROR') {
                            color = '#ef4444'; // 红色
                        } else if (log.level === 'WARN') {
                            color = '#f59e0b'; // 橙色
                        } else if (log.level === 'INFO') {
                            color = '#10b981'; // 绿色
                        }
                        
                        logLine.innerHTML = `<span style="color: #9ca3af;">${log.timestamp}</span> <span style="color: ${color}; font-weight: bold;">[${log.level}]</span> ${log.message}`;
                        logContainer.appendChild(logLine);
                        
                        // 自动滚动到底部
                        logContainer.scrollTop = logContainer.scrollHeight;
                        
                        // 限制日志条数（最多显示 200 条）
                        while (logContainer.children.length > 200) {
                            logContainer.removeChild(logContainer.firstChild);
                        }
                    } catch (e) {
                        console.error('解析日志失败:', e, event.data);
                    }
                };

                eventSourceInstance.onerror = (error) => {
                    console.error('❌ 日志连接错误:', error);
                    logContainer.innerHTML = '<div style="color: #ef4444;">❌ 日志连接失败，5秒后重试...</div>';
                    
                    if (eventSourceInstance) {
                        eventSourceInstance.close();
                        eventSourceInstance = null;
                    }
                    
                    // 5 秒后重连
                    setTimeout(connectLogs, 5000);
                };
            } catch (e) {
                console.error('创建 EventSource 失败:', e);
                logContainer.innerHTML = `<div style="color: #ef4444;">❌ 创建连接失败: ${e.message}</div>`;
            }
        }

        // 页面关闭时断开连接
        window.addEventListener('beforeunload', () => {
            if (eventSourceInstance) {
                eventSourceInstance.close();
            }
        });

        // ========== 会话管理 ==========
        async function loadConversations() {
            try {
                const response = await fetchWithAuth('/admin/api/conversations');
                const conversations = await response.json();
                
                const container = document.getElementById('conversationsList');
                
                if (conversations.length === 0) {
                    container.innerHTML = '<div style="padding: 20px; text-align: center; color: #999;">暂无会话记录</div>';
                    return;
                }
                
                let html = '<table style="width: 100%; border-collapse: collapse;"><thead><tr style="background: #f5f5f5;"><th style="padding: 12px; text-align: left;">会话 ID</th><th style="padding: 12px; text-align: left;">模型</th><th style="padding: 12px; text-align: left;">最后更新</th><th style="padding: 12px; text-align: center;">操作</th></tr></thead><tbody>';
                
                conversations.forEach(conv => {
                    const date = new Date(conv.lastUpdated);
                    const timeStr = date.toLocaleString('zh-CN');
                    html += `
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 12px; font-family: monospace; font-size: 13px;">${conv.chatHistoryId}</td>
                            <td style="padding: 12px;">${conv.model}</td>
                            <td style="padding: 12px;">${timeStr}</td>
                            <td style="padding: 12px; text-align: center;">
                                <button class="btn" style="background: #ef4444; padding: 6px 12px; font-size: 12px;" onclick="deleteConversation('${conv.chatHistoryId}')">🗑️ 删除</button>
                            </td>
                        </tr>
                    `;
                });
                
                html += '</tbody></table>';
                container.innerHTML = html;
            } catch (error) {
                alert('❌ 加载会话失败: ' + error.message);
            }
        }
        
        async function deleteConversation(chatHistoryId) {
            if (!confirm(`确定要删除会话 ${chatHistoryId} 吗？\n\n这将同时删除 cto.new 网站上的对话记录！`)) {
                return;
            }
            
            try {
                const response = await fetchWithAuth(`/admin/api/conversations/${chatHistoryId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    alert('✅ 会话已删除！');
                    loadConversations();
                    loadStats();
                } else {
                    const error = await response.json();
                    alert(`❌ 删除失败: ${error.error || error.message}`);
                }
            } catch (error) {
                alert('❌ 删除失败: ' + error.message);
            }
        }

        // 启动日志连接
        connectLogs();
    </script>
</body>
</html>


